<script setup>
import api from './api'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  modelValue: { type: Object, default: () => ({}) },
  field: { type: String, default: '' },
  wrap: Boolean,
  dialog: Boolean,
  disabled: Boolean,
})
const emit = defineEmits(['change'])
const keys = reactive({
  id: props.field ? props.field + '_area_id' : 'area_id',
  name: props.field ? props.field + '_area_name' : 'area_name',
  address: props.field ? props.field + '_address' : 'address',
})
const form = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})
const loadings = reactive({})

const change = () => {
  emit('change', form.value[keys.name].join(' ') +' '+ (form.value[keys.address] || ''))
}

const handleChange = ({ value, labels }) => {
  if (!value) {
    form.value[keys.name] = []
    return
  }
  form.value[keys.name] = labels
  change()
}

// 智能识别
const toSmart = async val => {
  let areas = val?.trim()
  let a_id = 0
  const ids = []
  const names = []
  while (ids.length < 3) {
    const res = await api.query({ parent_id: a_id })
    const item = res.data.find(d => areas.startsWith(d.area_name))
    if (!item) {
      ElMessage.error('识别失败')
      return
    }
    a_id = item.a_id
    areas = areas.replace(item.area_name, '')
    ids.push(a_id)
    names.push(item.area_name)
  }
  form.value[keys.id] = ids
  form.value[keys.name] = names
  form.value[keys.address] = areas
  change()
  ElMessage.success('填写成功')

}

const smart = async () => {
  if (props.dialog) {
    ElMessageBox.prompt('此处粘贴地址信息，可自动识别省/市/区+详细地址，如广东省深圳市XX区XX街道XX号', '智能填充', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern:
        /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
      inputErrorMessage: '填写有误',
    })
      .then(async ({ value }) => {
        loadings.smart = true
        await toSmart(value)
        loadings.smart = false
      })
  } else {
    loadings.smart = true
    await toSmart(form.value[keys.address])
    loadings.smart = false
  }
}
</script>

<template>
  <template v-if="wrap">
    <div class="flex flex-col" v-bind="$attrs">
      <v-group>
        <VCascader v-model="form[keys.id]" type="3" class="w-full" showAllLevels filterable clearable emitPath :disabled="disabled" @change="handleChange" />
        <el-button v-if="!disabled" type="primary" class="px-2" :loading="loadings.smart" @click="smart">智能填充</el-button>
      </v-group>
      <el-input v-model="form[keys.address]" placeholder="自动识别省/市/区+详细地址" clearable :disabled="disabled" class="mt-1" @change="change"></el-input>
    </div>
  </template>
  <v-group v-else class="w-full" v-bind="$attrs">
    <VCascader v-model="form[keys.id]" type="3" filterable clearable showAllLevels emitPath :disabled="disabled" class="w-80" @change="handleChange" />
    <el-input v-model="form[keys.address]" placeholder="自动识别省/市/区+详细地址" clearable :disabled="disabled" @change="change"></el-input>
    <el-button v-if="!disabled" type="primary" class="px-2" :loading="loadings.smart" @click="smart">智能填充</el-button>
  </v-group>
</template>